<template>
  <transition name="dialog-fade">
    <div v-show="visible" class="dialog-wrapper">
      <div class="dialog-container">
        <div class="dialog-header">
          <span>{{ title }}</span>
          <i class="close-icon" @click="handleClose">×</i>
        </div>
        <div class="dialog-body">
          <slot>{{ content }}</slot>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="handleCancel">取消</button>
          <button class="confirm-btn" @click="handleConfirm">确定</button>
        </div>
      </div>
    </div>
  </transition>
</template>

<script>
const DialogComponent = {
  props: {
    title: {
      type: String,
      default: '提示'
    },
    content: String,
    showCancel: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      visible: false
    }
  },
  methods: {
    show() {
      this.visible = true
      return new Promise((resolve) => {
        this.resolve = resolve
      })
    },
    handleClose() {
      this.visible = false
      this.resolve('close')
    },
    handleCancel() {
      this.visible = false
      this.resolve('cancel')
    },
    handleConfirm() {
      this.visible = false
      this.resolve('confirm')
    }
  }
}

const Dialog = {
  install(Vue) {
    const Constructor = Vue.extend(DialogComponent)

    Vue.prototype.$dialog = {
      show(options) {
        const instance = new Constructor({
          propsData: options
        }).$mount()

        document.body.appendChild(instance.$el)
        return instance.show()
      }
    }
  }
}

export default Dialog
</script>

<style scoped>
.dialog-wrapper {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 2000;
}

.dialog-container {
  position: relative;
  width: 480px;
  margin: 15vh auto 0;
  background: #fff;
  border-radius: 4px;
}

.dialog-header {
  padding: 20px 20px 10px;
  font-size: 18px;
  display: flex;
  justify-content: space-between;
}

.close-icon {
  cursor: pointer;
  font-style: normal;
}

.dialog-body {
  padding: 30px 20px;
  color: #606266;
  line-height: 24px;
}

.dialog-footer {
  padding: 10px 20px 20px;
  text-align: right;
}

.confirm-btn,
.cancel-btn {
  padding: 8px 15px;
  margin-left: 10px;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-btn {
  background: #409eff;
  color: #fff;
  border: 1px solid #409eff;
}

.cancel-btn {
  background: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
}

.dialog-fade-enter-active {
  animation: dialog-fade-in 0.3s;
}

.dialog-fade-leave-active {
  animation: dialog-fade-out 0.3s;
}

@keyframes dialog-fade-in {
  0% {
    opacity: 0;
    transform: translateY(-20px);
  }

  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes dialog-fade-out {
  0% {
    opacity: 1;
    transform: translateY(0);
  }

  100% {
    opacity: 0;
    transform: translateY(-20px);
  }
}
</style>
